package com.st.emps.achievements.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.st.emps.achievements.model.AchievementsModel;
import com.st.emps.project.model.ProjectModel;
import com.st.emps.util.JDBCUtil;

public class AchievementsDao {
	public int insert(AchievementsModel model) {
		String sql = "insert into achievements(code) values(?)";
		return JDBCUtil.update(sql,model.getCode());
	}
	public int delete(AchievementsModel model) {
	    String sql = "delete from achievements where code =?";
	    return JDBCUtil.update(sql,model.getCode());

	}
	public int update(AchievementsModel model) {
		String sql = "update achievements set score = ? where code= ?";
        return JDBCUtil.update(sql, model.getScore(),model.getCode());
	}
	public List<AchievementsModel> select(AchievementsModel model) {
		StringBuffer sql = new StringBuffer("select code,project_code,(select name from project where project_code=project.code) project_name,(select name from department where department.code in (select department_code from project where project_code=project.code)) department_name,score  from achievements where 1=1 ");
		List<Object> vals = appendWhere(sql,model);
        Map<String,String> fields = new HashMap<String,String>();
        fields.put("code", "code");
        fields.put("projectCode", "project_code");
        fields.put("projectName", "project_name");
        fields.put("departmentName", "department_name");
        fields.put("score", "score");
        return JDBCUtil.query(sql,vals,AchievementsModel.class,fields);
	}
	private List<Object> appendWhere(StringBuffer sql,AchievementsModel model) {
		List<Object> list = new ArrayList<Object>();
		String code = model.getCode();
		if(code!=null&&!code.trim().isEmpty()) {
			sql.append(" and code like ? ");
			list.add(code);
		}
		if(model.isPageOn()) {
			sql.append(" limit ?,? ");
			list.add(model.getRowStart());
			list.add(model.getPageLimit());
		}
		return list;
	}
	public Object selectCount(AchievementsModel model) {
		StringBuffer sql = new StringBuffer("select count(1) from achievements where 1=1 ");
		List<Object> list = appendWhere(sql,model);
		return JDBCUtil.queryInt(sql,list);
	}

	public int updateProject(AchievementsModel model) {
		String sql = "update achievements set project_code = ? where code = ? ";
		return JDBCUtil.update(sql, model.getProjectCode(),model.getCode());
	}
	public int updateDepart(AchievementsModel model) {
		String sql = "update achievements set department_code = (select department_code from project where project.code = achievements.project_code) where code = ? ";
		return JDBCUtil.update(sql, model.getCode());
	}
}